import { Injectable, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../entities/user.entity';
import { Sku } from '../entities/sku.entity';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { QueryUserDto } from './dto/query-user.dto';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private userRepository: Repository<User>,
  ) {}

  async findAll(query: QueryUserDto) {
    const { name, phone, skuId, page = 1, size = 10 } = query;
    const queryBuilder = this.userRepository
      .createQueryBuilder('user')
      .leftJoinAndSelect('user.skus', 'sku')
      .where('user.role = :role', { role: 'employee' });

    if (name) {
      queryBuilder.andWhere('user.name LIKE :name', { name: `%${name}%` });
    }

    if (phone) {
      queryBuilder.andWhere('user.phone LIKE :phone', { phone: `%${phone}%` });
    }

    if (skuId) {
      queryBuilder.andWhere('sku.id = :skuId', { skuId });
    }

    const [users, total] = await queryBuilder
      .skip((page - 1) * size)
      .take(size)
      .getManyAndCount();

    return {
      data: users,
      total,
      page,
      size,
    };
  }

  async create(createUserDto: CreateUserDto) {
    const { name, phone, skuIds } = createUserDto;

    if (!phone && !name) {
      throw new Error('姓名或手机号不能为空');
    }

    if (phone) {
      const existingUser = await this.userRepository.findOne({
        where: { phone },
      });
      if (existingUser) {
        throw new BadRequestException('该手机号已被使用');
      }
    }

    const user = this.userRepository.create({
      name,
      phone,
      role: 'employee',
      username: '',
      password: '',
    });

    if (skuIds && skuIds.length > 0) {
      user.skus = skuIds.map((id) => ({ id }) as Sku);
    }

    return this.userRepository.save(user);
  }

  async remove(id: number) {
    const user = await this.userRepository.findOne({ where: { id } });
    if (!user) {
      throw new Error('User not found');
    }
    return this.userRepository.remove(user);
  }

  async update(id: number, updateUserDto: UpdateUserDto) {
    const { name, phone, skuIds } = updateUserDto;
    const user = await this.userRepository.findOne({ where: { id } });
    if (!user) {
      throw new Error('User not found');
    }

    if (name) {
      user.name = name;
    }
    if (phone) {
      if (phone !== user.phone) {
        const existingUser = await this.userRepository.findOne({
          where: { phone },
        });
        if (existingUser) {
          throw new BadRequestException('该手机号已被使用');
        }
      }
      user.phone = phone;
    }
    if (skuIds) {
      user.skus = skuIds.map((id) => ({ id }) as Sku);
    }

    return this.userRepository.save(user);
  }
}
